package com.itcast.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.pojo.Admin;
import com.itcast.pojo.User;
import com.itcast.service.Userservice;
import com.itcast.utils.PoiUtil;
import com.itcast.utils.Respone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private Userservice userservice;

    @RequestMapping("/index")
    @ResponseBody
    public Map<String,Object> index() throws JsonProcessingException {
        Map<String, Object> map=new HashMap<>();
        return map;
    }


    @GetMapping("/list")
    public Respone list(@RequestParam("page") int page, @RequestParam("limit") int limit){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        Page<User> pageSize=new Page<>(page,limit);
        IPage<User> page1 = userservice.page(pageSize, queryWrapper);
        System.out.println((int)page1.getTotal());
        return new Respone(0,"成功",page1.getRecords(),(int)page1.getTotal());
    }

    @PostMapping("/update")
    public Respone update(@RequestBody User user){
        boolean update = userservice.updateById(user);
        if(update){
            return new Respone(0,"更新成功");
        }
        return new Respone(999,"更新失败");
    }

    @GetMapping("/delete")
    public Respone del(@RequestParam("uid") int uid){
        if(  userservice.removeById(uid)){
            return new Respone(0,"删除成功");
        }
        return new Respone(999,"删除失败");
    }

    @RequestMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response){
        List<User> list = userservice.list(null);
        PoiUtil.exportExcel(list,"用户列表","用户列表",User.class,"用户列表文件.xls",response);
    }

    @PostMapping("/add")
    public Respone add(@RequestBody User user){
        boolean save = userservice.save(user);
        if(save){
            return new Respone(0,"添加成功");
        }
        return new Respone(999,"添加失败");
    }


}

